﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class ForgotPasswordForm : Form
    {
        public ForgotPasswordForm()
        {
            InitializeComponent();
        }

        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtCDK.Text) || string.IsNullOrEmpty(txtNewPassword.Text) || string.IsNullOrEmpty(txtConfirmNewPassword.Text))
            {
                MessageBox.Show("所有字段均为必填");
                return;
            }

            if (txtNewPassword.Text != txtConfirmNewPassword.Text)
            {
                MessageBox.Show("新密码和确认新密码不一致");
                return;
            }

            if (ValidateCDK(txtUsername.Text, txtCDK.Text))
            {
                if (ResetPassword(txtUsername.Text, txtNewPassword.Text))
                {
                    MessageBox.Show("密码重置成功");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("密码重置失败");
                }
            }
            else
            {
                MessageBox.Show("CDK 无效或用户名不匹配");
            }
        }

        private bool ValidateCDK(string username, string cdk)
        {
            using (SqlConnection sqlConnection = DBConnection.CreateConnection())
            {
                sqlConnection.Open();
                using (SqlCommand cmd = sqlConnection.CreateCommand())
                {
                    cmd.Connection = sqlConnection;
                    cmd.CommandText = "SELECT COUNT(*) FROM CDK WHERE CDK = @cdk AND IsAvailable = 1 AND AvailableUses > 0";
                    cmd.Parameters.AddWithValue("@cdk", cdk);
                    int count = (int)cmd.ExecuteScalar();
                    return count > 0;
                }
            }
        }

        private bool ResetPassword(string username, string newPassword)
        {
            using (SqlConnection sqlConnection = DBConnection.CreateConnection())
            {
                sqlConnection.Open();
                using (SqlCommand cmd = sqlConnection.CreateCommand())
                {
                    cmd.Connection = sqlConnection;
                    cmd.CommandText = "UPDATE Users SET Password = @password WHERE AdminName = @username";
                    cmd.Parameters.AddWithValue("@username", username);
                    cmd.Parameters.AddWithValue("@password", newPassword);  // 直接存储明文密码
                    try
                    {
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("重置密码失败: " + ex.Message);
                        return false;
                    }
                }
            }
        }
    }
}
